#include "pch.h"
#include "Grid.h"
#include "DirectXTK\DirectXHelpers.h"
Grid::Grid(ID3D11Device* device, ID3D11DeviceContext* m_context,size_t div) 
    : m_device(device),m_context(m_context),divisions(div)
{
    m_world = Matrix::Identity;

    m_states = std::make_unique<CommonStates>(device);

    m_effect = std::make_unique<BasicEffect>(device);
    m_effect->SetVertexColorEnabled(true);

    DX::ThrowIfFailed(
        CreateInputLayoutFromEffect<VertexPositionColor>(device, m_effect.get(),
            m_inputLayout.ReleaseAndGetAddressOf())
    );

    m_batch = std::make_unique<PrimitiveBatch<VertexPositionColor>>(m_context);

    m_view = Matrix::CreateLookAt(Vector3(2.f, 2.f, 2.f),
        Vector3::Zero, Vector3::UnitY);
    m_proj = Matrix::CreatePerspectiveFieldOfView(XM_PI / 4.f,
        16.0f/9.0f, 0.1f, 100.f);

    m_effect->SetView(m_view);
    m_effect->SetProjection(m_proj);
}

Grid::~Grid()
{

}

void Grid::Draw()
{
    m_context->OMSetBlendState(m_states->Opaque(), nullptr, 0xFFFFFFFF);
    m_context->OMSetDepthStencilState(m_states->DepthNone(), 0);
    m_context->RSSetState(m_states->CullNone());

    m_effect->SetWorld(m_world);

    m_effect->Apply(m_context.Get());

    m_context->IASetInputLayout(m_inputLayout.Get());

    m_batch->Begin();

    Vector3 xaxis(10.f, 0.f, 0.f);
    Vector3 yaxis(0.f, 0.f, 10.f);
    Vector3 origin = Vector3::Zero;

    for (size_t i = 0; i <= divisions; ++i)
    {
        float fPercent = float(i) / float(divisions);
        fPercent = (fPercent * 2.0f) - 1.0f;

        Vector3 scale = xaxis * fPercent + origin;

        VertexPositionColor v1(scale - yaxis, Colors::White);
        VertexPositionColor v2(scale + yaxis, Colors::White);
        m_batch->DrawLine(v1, v2);
    }

    for (size_t i = 0; i <= divisions; i++)
    {
        float fPercent = float(i) / float(divisions);
        fPercent = (fPercent * 2.0f) - 1.0f;

        Vector3 scale = yaxis * fPercent + origin;

        VertexPositionColor v1(scale - xaxis, Colors::White);
        VertexPositionColor v2(scale + xaxis, Colors::White);
        m_batch->DrawLine(v1, v2);
    }

    m_batch->End();
}
